package com.ias.agdis_r.action.task;

import android.content.Context;

import com.ias.agdis_r.R;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.task.TRST;
import com.ias.agdis_r.bean.task.TTUD;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.bean.task.TaskField;
import com.ias.agdis_r.bean.task.TaskForward;
import com.ias.agdis_r.bean.task.TaskInfo;
import com.ias.agdis_r.bean.task.TaskInfo.TaskInfoEnum;
import com.ias.agdis_r.bean.task.TaskProcess;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.db.BoxDBHelper;
import com.ias.agdis_r.manager.ActionManager;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.FindLuggageDataManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.manager.ThreadManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.temple.XmlHelper;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.SubmittaskprocssRequest;
import com.ias.agdis_r.terminalmanager.restful.task.vo.SubmitTaskProcessRequestVO;
import com.ias.agdis_r.util.FlnChangeUtils;
import com.ias.agdis_r.util.MyMessage;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.TaskUtil;
import com.ias.agdis_r.util.network.HttpUtil;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

public class TaskReceiveAction {
    private static TaskReceiveAction instance;
    private ObjectMapper mapper = DataManager.getInstance().getMapper();
    private Context context = DataBaseManager.getInstance().getContext();

	/**
	 * 单例模式
	 * 
	 * @return
	 */
	public static TaskReceiveAction getInstance() {
		if (instance == null) {
			instance = new TaskReceiveAction();
		}
		// 如果模板为空
		if (XmlHelper.getInstance().getTaskViewTemp() == null) {
			XmlHelper.getInstance().loadTaskXML();
		}
		return instance;
	}

	/**
	 * 接收-下发任务消息
	 * @param task
	 * @param serviecId
	 * @param sdt
	 */
	public void receiveTask(final Task task, final String serviecId,String sdt) {
		if (!ServiceManage.getInstance().getIsLogon()) {
			// 如果未登录，不继续执行
			return;
		} else if (DataManager.getInstance().hasTask(task.getTNB())||DataManager.getInstance().hasNFTask(task.getTNB())) {
			return;
		}

        if (task.getProcessMap().size() < 1) {
            EffectManager.getInstance().ttsPlay(
                    EffectManager.TTS_TYPE_TEMP,
                    context.getString(R.string.TRA_1) + FlnChangeUtils.flnChangeUtils(task.getTaskInfo().getFLN(),DataBaseManager.getInstance().getContext())
                            + task.getTaskInfo().getRNM() + context.getString(R.string.TRA_2)
                            + task.getTNB() + context.getString(R.string.TRA_3), true);
            return;
        } else {
            // 进程节点RESTFUL返回结果顺序有误，进行排序
            LinkedHashMap<String, TaskProcess> processMap = (LinkedHashMap<String, TaskProcess>) task
                    .getProcessMap();
            LinkedHashMap<String, TaskProcess> sortProcessMap = TaskUtil
                    .processSort(processMap);
            task.setProcessMap(sortProcessMap);
        }

		if(task.getTaskFields()!=null&&task.getTaskFields().size()>0) {
			//任务扩展信息排序
			LinkedHashMap<String, TaskField> fieldMap = task.getTaskFields();
			fieldMap = TaskUtil.taskFieldSort(fieldMap);
			task.setTaskFields(fieldMap);
		}
		String event  = S.valueOf(task.getEVENT());

		if (event.equals("Y")) {
			// 通用任务
			TaskUtil.shortServiceLabelMap(task);
			receiveNFTask(task, serviecId, sdt);
		} else {
			// 航班任务
			receiveFlightTask(task, serviecId, sdt);
			// 如果具有翻行李权限
			if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_LUGGAGEFIND.toString())) {
				//保存需要初始化翻行李信息的任务号
				FindLuggageDataManager.getInstance().saveFindLuggageTnb(task.getTNB());
			}
		}
	}


	/**
	 * 接收-下发航班任务消息
	 * @param task
	 * @param serviecId
	 * @param sdt
	 */
	private void receiveFlightTask(final Task task, final String serviecId,String sdt){

		//已转发过的转发任务节点名称改为“已转”
		if (MessageModel.ZFYJ_TYPE_G.equals(JavaBeanManager.getInstance().getUserinfo().getTtr())) {
			List<TaskForward> tfList = JavaBeanManager.getInstance().getTaskForwardList();
			for (TaskForward taskForward : tfList) {
				if (task.getTNB().equals(taskForward.getTnb())) {
					TaskProcess taskProcess = task.getProcess(taskForward.getPcid());
					if (taskProcess != null) {
						taskProcess.setPCNM(taskForward.getPcnm());
					}
				}
			}
		}
		// 播放接收任务铃声
		playEffect(MessageModel.ITSD);
		UserInfoBean userinfo = JavaBeanManager.getInstance().getUserinfo();
		if (userinfo != null && task.getTaskInfo() != null) {
			//如果用户的车号不为空，保存车号
			String vnb = userinfo.getVnb();
			task.getTaskInfo().setVNB(vnb);
		}
		// 保存接收的任务
		if (task.getPID().equals(MessageModel.TDWN)
				|| task.getPID().equals(MessageModel.TRPE)
				|| task.getPID().equals(MessageModel.TFAL)) {
			// 发送TGET
			SubmittaskprocssRequest submittaskprocssRequest = new SubmittaskprocssRequest();
			submittaskprocssRequest = new SubmittaskprocssRequest();
			SubmitTaskProcessRequestVO submittaskprocssrequestVO = new SubmitTaskProcessRequestVO();
			submittaskprocssrequestVO.setIFM("");
			submittaskprocssrequestVO.setPID(MessageModel.TGET);
			submittaskprocssrequestVO.setRMK(null);
			submittaskprocssrequestVO.setSDT(S.getNowTime());
			submittaskprocssrequestVO.setTNB(task.getTNB());
			submittaskprocssrequestVO.setTST("S");
			submittaskprocssRequest
					.setSubmittaskprocssRequestVO(submittaskprocssrequestVO);
			HttpUtil.getInstance().sendRequest(submittaskprocssRequest,
					MessageModel.TRPT, true);
//            String lastReceiveTaskInfo = MessageManager.getInstance()
//                    .getTaskMessage(task.getTNB(), MessageModel.TREC, null);
//            ServiceManage.getInstance().sendMessage(lastReceiveTaskInfo, true,
//                    null);
			DataManager.getInstance().saveReceiveTask(task.getTNB(), task);
			saveMessage(task,sdt,false);
		} else {
			DataManager.getInstance().saveWorkTask(task.getTNB(), task);
			if (MessageModel.TTSD.equals(serviecId)){
				saveMessage(task,sdt,false);
			}
		}
		// 如果有打印单据权限,申请单据的版本信息
		if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_DOCPRINT.toString())) {
			TaskInfo taskInfo = task.getTaskInfo();
			if (taskInfo != null) {
				// 保存该任务对应的航班号，用于申请单据
				String fke = task.getTaskInfo().getFKE();
				// 如果FKE不为空，且没有存储单据的信息
				if (S.isNotEmpty(fke)
						&& DataManager.getInstance().getDocList(fke) == null) {
					DataManager.getInstance().putDocList(
							task.getTaskInfo().getFKE(), null);
				}
			}
		}
		ActionManager.getInstance().updateUI(serviecId);
		ThreadManager.getInstance().resleepForIQRYThread(10);// 重新
	}

	/**
	 * 接收-下发通用任务消息
	 * @param task
	 * @param serviecId
	 * @param sdt
	 */
	private void receiveNFTask(final Task task, final String serviecId,String sdt){

		// 播放接收任务铃声
		playEffect(MessageModel.ITSD);
		UserInfoBean userinfo = JavaBeanManager.getInstance().getUserinfo();
		if (userinfo != null && task.getTaskInfo() != null) {
			//如果用户的车号不为空，保存车号
			String vnb = userinfo.getVnb();
			task.getTaskInfo().setVNB(vnb);
		}
		// 保存接收的任务
		if (task.getPID().equals(MessageModel.T_EDWN)
				|| task.getPID().equals(MessageModel.T_ERPE)
				|| task.getPID().equals(MessageModel.T_EFAL)) {
			// 发送TGET
			SubmittaskprocssRequest submittaskprocssRequest = new SubmittaskprocssRequest();
			submittaskprocssRequest = new SubmittaskprocssRequest();
			SubmitTaskProcessRequestVO submittaskprocssrequestVO = new SubmitTaskProcessRequestVO();
			submittaskprocssrequestVO.setIFM("");
			submittaskprocssrequestVO.setPID(MessageModel.T_EGET);
			submittaskprocssrequestVO.setRMK(null);
			submittaskprocssrequestVO.setSDT(S.getNowTime());
			submittaskprocssrequestVO.setTNB(task.getTNB());
			submittaskprocssrequestVO.setTST("S");
			submittaskprocssRequest
					.setSubmittaskprocssRequestVO(submittaskprocssrequestVO);
			HttpUtil.getInstance().sendRequest(submittaskprocssRequest,
					MessageModel.TRPT, true);
			DataManager.getInstance().saveReceiveNFTask(task.getTNB(), task);
			saveMessage(task,sdt,true);
		} else {
			DataManager.getInstance().saveWorkNFTask(task.getTNB(), task);
			if (MessageModel.TTSD.equals(serviecId)){
				saveMessage(task,sdt,true);
			}
		}
		ActionManager.getInstance().updateUI(serviecId);
		ThreadManager.getInstance().resleepForIQRYThread(10);// 重新
	}

	private void saveMessage(Task task, String sdt,boolean isNF){
		String msg = "";
		//通用任务
		if(isNF){
			msg = context.getString(R.string.TRA_15) + task.getTaskInfo().getTTP() + context.getString(R.string.TRA_5)
					+ task.getTaskInfo().getTNM() + context.getString(R.string.TRA_16);
		}else{
			msg =  context.getString(R.string.TRA_4) + task.getTaskInfo().getFLN() + context.getString(R.string.TRA_5)
					+ task.getTaskInfo().getRNM() + context.getString(R.string.TRA_6);
		}
		EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, msg, true);
		TaskInfo mtaskInfo = task.getTaskInfo();
		if (null != mtaskInfo) {
			saveData(task.getTNB(), msg, MessageModel.TTSD, sdt, mtaskInfo.getFKE(), mtaskInfo.getFLN());
		} else {
			saveData(task.getTNB(), msg, MessageModel.TTSD, sdt, null, null);
		}
	}

	public boolean receiveTTSD(String message) {
		String sdt = MyMessage.getValue(message, MessageModel.SDT, 3);
		String serviceId = MessageModel.TTSD;
		String sem = MyMessage.getValue(message, MessageModel.SEM, 3);
		String sTask = MyMessage.getTxtContent(message);
		if (S.isEmpty(sTask)) {
			return false;
		}
		try {
            Task receiveTask = mapper.readValue(sTask, Task.class);
            String tnb = receiveTask.getTNB();
            receiveTask.getTaskInfo().setSEM(sem);
            DataManager.getInstance().removeResponseTnb(tnb);
            // 写入任务进展数据
//            BoxDBHelper dbHelper = new BoxDBHelper(DataBaseManager.getInstance().getContext());
//            dbHelper.setTaskProcessDate(tnb, context.getString(R.string.taskPublish), context.getString(R.string.BRA_3) + receiveTask.getTaskInfo().getFLN() + context.getString(R.string.BRA_4) + receiveTask.getTaskInfo().getRNM() + context.getString(R.string.TRA_7));
			receiveTask(receiveTask, serviceId, sdt);
        } catch (JsonParseException e1) {
            e1.printStackTrace();
        } catch (JsonMappingException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }

	public boolean receiveITSD(String message) {
//		String serviceId = MessageModel.ITSD;
//		String sidx = MyMessage.getValue(message, MessageModel.IDX, 3);
//		String sem = MyMessage.getValue(message, MessageModel.SEM, 3);
//		if ("0".equals(sidx)) {
//			MessageManager.getInstance().setLastIQRYMessage(null);
//			JavaBeanManager.getInstance().saveFLG4Info("0");
//			String msg3 = MessageManager.getInstance().getFLG3IQRYMessage(null);
//			ServiceManage.getInstance().sendMessage(msg3);
//			return true;
//		}
//		String sTask = MyMessage.getTxtContent(message);
//		if (S.isEmpty(sTask)) {
//			return false;
//		}
//		try {
//			Task receiveTask = mapper.readValue(sTask, Task.class);
//			String tnb = receiveTask.getTNB();
//			receiveTask.getTaskInfo().setSEM(sem);
//			if (receiveTask.getProcessMap().size() < 1) {
//				EffectManager.getInstance()
//						.ttsPlay(
//								EffectManager.TTS_TYPE_TEMP,
//								"刚收到未完成的航班"
//										+ FlnChangeUtils.flnChangeUtils(receiveTask.getTaskInfo().getFLN(),context)
//										+ receiveTask.getTaskInfo().getRNM()
//										+ "任务" + receiveTask.getTNB()
//										+ "未包含有效执行节点，请确认后台配置变化。", true);
//				return false;
//			}
//			if (S.isEmpty(tnb)) {
//				return false;
//			} else if (DataManager.getInstance().hasTask(tnb)) {
//				return false;
//			} else {
//				// 指定IQRY线程的暂停时间
//				ThreadManager.getInstance().resleepForIQRYThread(10 * 1000);// 重新
//				MessageManager.getInstance().setLastIQRYMessage(null);
////				if (receiveTask.getPID().equals(MessageModel.TDWN)) {
////					// 自动发送"收到"
////					String lastReceiveTaskInfo = MessageManager.getInstance()
////							.getTaskMessage(receiveTask.getTNB(),
////									MessageModel.TREC, null);
////					ServiceManage.getInstance().sendMessage(
////							lastReceiveTaskInfo, true, null);
////				}
//				int idx = Integer.valueOf(sidx);
//				if (idx > 0) {
//					// IDX减1后，保存
//					JavaBeanManager.getInstance().saveFLG4Info(
//							S.valueOf(idx - 1));
//					IQRYInfoBean iqryInfo = JavaBeanManager.getInstance()
//							.getIQRYinfo();
//					if (iqryInfo.getIdxFlg4() != null) {
//						String flg4 = MessageManager.getInstance()
//								.getFLG4IQRYMessage(iqryInfo.getIdxFlg4());
//						ServiceManage.getInstance().sendMessage(flg4);
//					}
//				}
//				// 接收Task
//				receiveTask(receiveTask, serviceId);
//			}
//		} catch (JsonParseException e1) {
//			e1.printStackTrace();
//		} catch (JsonMappingException e1) {
//			e1.printStackTrace();
//		} catch (IOException e1) {
//			e1.printStackTrace();
//		}
		return false;
	}

	public void playEffect(String type) {
		if (type.equals(MessageModel.BDWI)) {
			int product = EffectManager.RECEIVE_PRODUCT_TYPE;// 收到生产通告时(0：震动
			// 1：声音,2：震动+声音)
			if (product == 0) {
				EffectManager.getInstance().vibrate();
			} else if (product == 1) {
				EffectManager.getInstance().playSound(
						ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
			} else {
				EffectManager.getInstance().vibrate();
				EffectManager.getInstance().playSound(
						ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
			}

		} else if (type.equals(MessageModel.GWSM)) {
//			int info = EffectManager.RECEIVE_INFO_TYPE;// 收到消息时(0：震动
//			// 1：声音,2：震动+声音)
//
//			if (info == 0) {
//				EffectManager.getInstance().vibrate();
//			} else if (info == 1) {
//				EffectManager.getInstance().playSound(
//						ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
//			} else {
//				EffectManager.getInstance().vibrate();
//				EffectManager.getInstance().playSound(
//						ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
//			}
			EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
		} else {// 处理收到任务
//			EffectManager.getInstance().vibrate();
//			EffectManager.getInstance().playSound(
//					ParameterModel.MUSIC_EFFECT_RECEIVE_TASK);
			EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_RECEIVE_TASK);
		}
	}

	/**
	 * 任务内容变更
	 * 
	 * @param message
	 */
	public boolean receiveTTUD(String message) {
		String sdt = MyMessage.getValue(message, MessageModel.SDT, 3);
		String ttud = MyMessage.getTxtContent(message);
		if (S.isEmpty(ttud)) {
			return false;
		}
		TTUD ttudJson = null;
		Task receiveTask = null;
		if (S.isEmpty(ttud)) {
			return false;
		}
		try {
			ttudJson = mapper.readValue(ttud, TTUD.class);
			receiveTask = ttudJson.getTask();
			String tnb = receiveTask.getTNB();
			if (!DataManager.getInstance().hasTask(tnb)) {
				return false;
			} else {

				Task oldTask = DataManager.getInstance().getWorkTask(tnb);
				if (oldTask == null) {
					oldTask = DataManager.getInstance().getReceiveTask(tnb);
				}

                if (oldTask == null) {
                    oldTask = DataManager.getInstance().getHistoryWorkTask(tnb);
                }
                if (oldTask == null) {
                    return false;
                }
                updateTaskInfo(oldTask, receiveTask);
				updateTaskField(oldTask, receiveTask);
                String msg = ttudJson.getMsg();
                // 写入任务进展数据
//                BoxDBHelper dbHelper = new BoxDBHelper(DataBaseManager.getInstance().getContext());
//                dbHelper.setTaskProcessDate(tnb, context.getString(R.string.ttud), msg);
                // 播放提示音
                TaskReceiveAction.getInstance().playEffect(MessageModel.TTUD);
                EffectManager.getInstance().ttsPlay(
                        EffectManager.TTS_TYPE_TASK, context.getString(R.string.ttud), false);
                TaskInfo taskInfo = receiveTask.getTaskInfo();
                if (null != taskInfo) {
                    saveData(tnb, msg, MessageModel.TTUD, sdt, taskInfo.getFKE(), taskInfo.getFLN());
                } else {
                    saveData(tnb, msg, MessageModel.TTUD, sdt, null, null);
                }
            }
        } catch (JsonParseException e1) {
            e1.printStackTrace();
        } catch (JsonMappingException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (Exception e2) {
            e2.printStackTrace();
        }

		return true;
	}

	private void saveData(String tnb, String msg, String serviceId, String sdt,String fke, String fln) {
		BoxDBHelper dbHelper = new BoxDBHelper(DataBaseManager.getInstance()
				.getContext());
		dbHelper.setTaskData(tnb, msg, serviceId, sdt, fke, fln);
		dbHelper.closeDB();
		DataManager.getInstance().addUnCheckNumber();
		// 刷新任务列表UI或者刷新任务详情UI
		ActionManager.getInstance().refreshBox(MessageModel.REFRESH);
		ActionManager.getInstance().updateUI(MessageModel.REFRESH,tnb);
	}

	public void updateTaskInfo(Task task, Task newTask) {

		if (task != null && newTask != null) {
			TaskInfo newTaskInfo = newTask.getTaskInfo();
			TaskInfo oldTaskInfo = task.getTaskInfo();

			for (TaskInfoEnum tag : TaskInfoEnum.values()) {
				String value = newTaskInfo.getString(tag);
				// 如果取值不为空，修改任务变更后的值
				if (value != null) {
					oldTaskInfo.setString(tag, value);
				}
			}
		}

	}

	public void updateTaskField(Task task, Task newTask) {

		if (task != null && newTask != null) {
			LinkedHashMap<String,TaskField>  newTaskFields = newTask.getTaskFields();
			LinkedHashMap<String,TaskField> oldTaskFields = task.getTaskFields();

			if(newTaskFields==null) {
				return;
			}
			if(oldTaskFields==null) {
				oldTaskFields = newTaskFields;
			}else{
				oldTaskFields.putAll(newTaskFields);
			}

			if(oldTaskFields!=null&&oldTaskFields.size()>0) {
				oldTaskFields = TaskUtil.taskFieldSort(oldTaskFields);
				task.setTaskFields(oldTaskFields);
			}
		}
	}


	/**
	 * 接收TRST消息（任务进程状态变更）,不再删除拒绝或取消的任务
	 *
	 * @param message
	 */
	public boolean receiveTRST(String message) {
        String stm = S
                .valueOf(MyMessage.getValue(message, MessageModel.STM, 3));
        String sdt = MyMessage.getValue(message, MessageModel.SDT, 3);
        String trst = MyMessage.getTxtContent(message);

        if (S.isEmpty(trst)) {
            return false;
        }
        TRST trstJson = null;
        Task updateTask;
        try {
            trstJson = mapper.readValue(trst, TRST.class);
            updateTask = trstJson.getTask();

            Task oldTask = DataManager.getInstance().getWorkTask(
                    updateTask.getTNB());

            if (oldTask == null) {
                oldTask = DataManager.getInstance().getReceiveTask(
                        updateTask.getTNB());
            }

            if (oldTask == null) {
                oldTask = DataManager.getInstance().getHistoryWorkTask(
                        updateTask.getTNB());
            }
            if (oldTask == null) {
                oldTask = DataManager.getInstance().getWorkNFTask(updateTask.getTNB());
            }
            if (oldTask == null) {
                oldTask = DataManager.getInstance().getReceiveNFTask(updateTask.getTNB());
            }
            if (oldTask == null) {
                oldTask = DataManager.getInstance().getNFHistoryWorkTask(updateTask.getTNB());
            }
            if (oldTask == null) {
                return false;
            }

            String oldpid = oldTask.getPID();
            String oldpnm = oldTask.getProcess(oldpid).getPCNM();
            String newpid = updateTask.getPID();
            String newpnm = updateTask.getProcess(newpid).getPCNM();
            if (!"Y".equals(updateTask.getEVENT())) {
                if (!oldpid.equals(MessageModel.TEND) // 非结束、拒绝或取消的任务都允许修改进程节点
                        && !oldpid.equals(MessageModel.TRJT)
                        && !oldpid.equals(MessageModel.TCXX) && !(oldpid.equals(newpid) && oldpnm.equals(newpnm))) {
                    oldTask.setPID(newpid);

                    HashMap<String, TaskProcess> newProcessMap = updateTask
                            .getProcessMap();

                    // 替换PID之后的所有节点
                    Iterator<Entry<String, TaskProcess>> iter = oldTask
                            .getProcessMap().entrySet().iterator();
                    boolean rf = false;
                    while (iter.hasNext()) {
                        Entry<String, TaskProcess> item = iter.next();
                        String key = item.getKey();
                        TaskProcess process = item.getValue();
                        if ("Y".equals(process.getIFSW())) {
                            if (key.equals(oldpid) || rf == true) {
                                iter.remove();
                                rf = true;
                            }
                        }

                    }
                    oldTask.getProcessMap().putAll(newProcessMap);
                    updateTaskList(updateTask.getTNB(), newpid, null);
                    if (oldpnm != null && newpnm != null) {
                        String msg = context.getString(R.string.BRA_3) + oldTask.getTaskInfo().getFLN() + context.getString(R.string.BRA_4)
                                + oldTask.getTaskInfo().getRNM() + context.getString(R.string.TRA_9) + oldpnm
                                + context.getString(R.string.TRA_10) + newpnm + context.getString(R.string.TRA_11);
                        // 播放提示音
                        TaskReceiveAction.getInstance().playEffect(MessageModel.TRST);
                        EffectManager.getInstance().ttsPlay(
                                EffectManager.TTS_TYPE_TASK, context.getString(R.string.trst), false);

                        TaskInfo taskInfo = updateTask.getTaskInfo();
                        if (null != taskInfo) {
                            saveData(updateTask.getTNB(), msg, MessageModel.TRST, sdt, taskInfo.getFKE(), taskInfo.getFLN());
                        } else {
                            saveData(updateTask.getTNB(), msg, MessageModel.TRST, sdt, null, null);
                        }
                    }
                }
            } else {
                if (!oldpid.equals(MessageModel.T_EEND) // 非结束、拒绝或取消的任务都允许修改进程节点
                        && !oldpid.equals(MessageModel.T_ERJT)
                        && !oldpid.equals(MessageModel.T_ECXX) && !(oldpid.equals(newpid) && oldpnm.equals(newpnm))) {
                    oldTask.setPID(newpid);

                    HashMap<String, TaskProcess> newProcessMap = updateTask
                            .getProcessMap();

                    // 替换PID之后的所有节点
                    Iterator<Entry<String, TaskProcess>> iter = oldTask
                            .getProcessMap().entrySet().iterator();
                    boolean rf = false;
                    while (iter.hasNext()) {
                        Entry<String, TaskProcess> item = iter.next();
                        String key = item.getKey();
                        TaskProcess process = item.getValue();
                        if ("Y".equals(process.getIFSW())) {
                            if (key.equals(oldpid) || rf == true) {
                                iter.remove();
                                rf = true;
                            }
                        }

                    }
                    oldTask.getProcessMap().putAll(newProcessMap);
                    updateTaskList(updateTask.getTNB(), newpid, null);
                    if (oldpnm != null && newpnm != null) {
                        String msg = context.getString(R.string.TRA_17)
                                + oldTask.getTaskInfo().getTNM() + context.getString(R.string.TRA_9) + oldpnm
                                + context.getString(R.string.TRA_10) + newpnm + context.getString(R.string.TRA_11);
                        // 播放提示音
                        TaskReceiveAction.getInstance().playEffect(MessageModel.TRST);
                        EffectManager.getInstance().ttsPlay(
                                EffectManager.TTS_TYPE_TASK, context.getString(R.string.trst), false);
                        saveData(updateTask.getTNB(), msg, MessageModel.TRST, sdt, null, null);
                    }
                }
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public void updateTaskList(String tnb, String pid, String atim) {
		if (DataManager.getInstance().hasTask(tnb)) {
			Task task = DataManager.getInstance().getReceiveTask(tnb);
			if (task == null) {
				task = DataManager.getInstance().getWorkTask(tnb);
			}
			if (task == null) {
				task = DataManager.getInstance().getReceiveNFTask(tnb);
			}
			if (task == null) {
				task = DataManager.getInstance().getWorkNFTask(tnb);
			}
			// 根据PID保存对应的监控项上报节点时间
			TaskProcess process = task.getProcess(pid);
			if (process != null && "N".equals(process.getIFSW())) {
				if (S.isNotEmpty(atim)) {
					process.setATIM(atim);
				} else {
					process.setATIM(S.getNowTime3());
				}

				// 如果是上报监控项的结果，不继续向下继续执行
				return;
			}
			// 保存任务节点
			task.setPID(pid);
//            // 写入任务进展数据
//            BoxDBHelper dbHelper = new BoxDBHelper(DataBaseManager.getInstance().getContext());
//            String pcnm = task.getProcess(pid).getPCNM();
//            dbHelper.setTaskProcessDate(tnb, context.getString(R.string.TRA_12) + pcnm, context.getString(R.string.BRA_3) + task.getTaskInfo().getFLN() + context.getString(R.string.BRA_4) + task.getTaskInfo().getRNM() + context.getString(R.string.TRA_13) + pcnm + context.getString(R.string.TRA_14));
			if ("Y".equals(task.getEVENT())) {
				if (pid.equals(MessageModel.T_EDWN) /* || pid.equals(MessageModel.TREC) */
						|| pid.equals(MessageModel.T_ERPE)
						|| pid.equals(MessageModel.T_EFAL)) {
					// 删除工作任务列表中的任务
					DataManager.getInstance().delNFWorkTask(tnb);
					// 保存到接收任务列表中
					DataManager.getInstance().saveReceiveNFTask(tnb, task);
				}// 如果是拒绝/取消的任务，暂时先不处理
				else if (pid.equals(MessageModel.T_EEND)
						|| pid.equals(MessageModel.T_ERJT)
						|| pid.equals(MessageModel.T_ECXX)
						|| TaskUtil.getNextTaskNode(task) == null) {
					DataManager.getInstance()
							.saveNFTaskHistoryWorkList(tnb, task);
					// 删除工作任务列表中的任务
					DataManager.getInstance().delNFWorkTask(tnb);
					DataManager.getInstance().delNFReceiveTask(tnb);
				} else {
					// 删除接受任务列表中的任务
					DataManager.getInstance().delNFReceiveTask(tnb);
					// 保存到工作任务列表中
					DataManager.getInstance().saveWorkNFTask(tnb, task);
				}
			} else {
				// 如果状态为 下发、收到、预派、发送失败
				if (pid.equals(MessageModel.TDWN) /* || pid.equals(MessageModel.TREC) */
						|| pid.equals(MessageModel.TRPE)
						|| pid.equals(MessageModel.TFAL)) {
					// 删除工作任务列表中的任务
					DataManager.getInstance().delWorkTask(tnb);
					// 保存到接收任务列表中
					DataManager.getInstance().saveReceiveTask(tnb, task);
				}
				// 如果是拒绝/取消的任务，暂时先不处理
				else if (pid.equals(MessageModel.TEND)
						|| pid.equals(MessageModel.TRJT)
						|| pid.equals(MessageModel.TCXX)
						|| TaskUtil.getNextTaskNode(task) == null) {
					DataManager.getInstance()
							.saveTaskHistoryWorkList(tnb, task);
					JavaBeanManager.getInstance().deleteRelativeTask(task);

					// 删除工作任务列表中的任务
					DataManager.getInstance().delWorkTask(tnb);

					DataManager.getInstance().delReceiveTask(tnb);
				} else {
					// 删除接受任务列表中的任务
					DataManager.getInstance().delReceiveTask(tnb);
					// 保存到工作任务列表中
					DataManager.getInstance().saveWorkTask(tnb, task);
				}
			}
		}
	}
}
